import { MutableRefObject, useEffect, useRef, useState } from 'react'
// import './chat.scss'
import ChatItem from '../../component/chatItem/chatItem'
import ChatSearch from '../chat/search/search'
import Notice from '../../component/notice/notice'
import axios from '../../util/http'
import socket from '../../util/socket'
import { useLocation } from 'react-router-dom'
import { formatQuery } from '../../util/util'
type TChatRoomItem = {
  UserId: number
  avatar: string
  id: number
  content: string
  realname: string
  time: string
  toUser: string
  type?: string
}
const Socket = () => {
  useEffect(() => {
    getSocketRoomList()
    tokeContent()
    initJoinRoom()
  }, [])
  const chatDom: MutableRefObject<HTMLDivElement | null> = useRef(null)
  const scrollDom: MutableRefObject<HTMLDivElement | null> = useRef(null)
  const [roomList, setRoomList] = useState<Array<TChatRoomItem>>([])
  const getSocketRoomList = () => {
    axios.get('/chatRoom/search').then(res => {
      setRoomList(res.data.data)
    })
  }
  const initJoinRoom = () => {
    socket.emit('online', {
      roomType: 'many'
    })
  }
  //正在谈话
  const tokeContent = () => {
    socket.on('message', data => {
      console.log(data)
      setRoomList(pre => [...pre, { ...data }])
    })
  }
  const sendMessage = (value: string) => {
    if (value.trim() === '') {
      return
    }
    // axios
    //   .get('/chat/add', {
    //     params: {
    //       username,
    //       content: value,
    //       to: currentRoom
    //     },
    //     headers: {
    //       Authorization: `Bearer ${token}`
    //     }
    //   })
    //   .then(res => {
    //     res.data.error === -1 &&
    //       socket.emit('message', {
    //         msg: value,
    //         username: currentRoom,
    //         realname,
    //         avatar,
    //         id: parseInt(userId),
    //         roomType: 'single'
    //       })
    //   })
  }
  return (
    <div className="chat" ref={chatDom}>
      <div ref={scrollDom}>
        {roomList.map((item, index) =>
          item.type !== 'notice' ? (
            <ChatItem
              message={item.content}
              direction={item.UserId * 1 !== parseInt('1') ? 'left' : 'right'}
              imgSrc={item.avatar}
              realname={item.realname}
              key={index + ''}
            ></ChatItem>
          ) : (
            <Notice message={item.content} key={index + Math.random()}></Notice>
          )
        )}
        <ChatSearch sendMessage={sendMessage}></ChatSearch>
      </div>
    </div>
  )
}

export default Socket
